//
//  VerificationVC.m
//  DataStatistics
//
//  Created by Kang on 16/3/10.
//  Copyright © 2016年 YTYangK. All rights reserved.
//

#import "VerificationVC.h"
#import <SMS_SDK/SMSSDK.h>
#import "LoginViewModel.h"

@interface VerificationVC () <UITextFieldDelegate, UIAlertViewDelegate,UIGestureRecognizerDelegate> {
    
    
    BOOL isClick;
    CGRect frameDefault;
    IBOutlet NSLayoutConstraint* V_nextView_H;
}
@property (strong, nonatomic) UIToolbar  * VVCtoolbar;
@property (strong, nonatomic) UIButton   * VVCbuton;
@property (strong, nonatomic) IBOutlet NSLayoutConstraint* V_verCode;
@property (strong, nonatomic) IBOutlet UILabel* timeLabel;
//计时
@property (nonatomic, strong) NSTimer* timer;
@property (nonatomic, strong) NSTimer* timer2;
@end

// 计时初始值
static int timerCount = 0;
@implementation VerificationVC

- (void)viewDidLoad {
    [super viewDidLoad];
    [self updateUI];
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}
- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    if (SYSTEM_VERSION_LESS_THAN_OR_EQUAL_TO_W_orH(SCREEN_HEIGHT, @"568.0")) {
        V_nextView_H.constant = 30; //-= 10;
        if (SCREEN_HEIGHT == 480) {
            _V_verCode.constant += 9;
        }
    }
}
- (void)viewDidAppear:(BOOL)animated {
    [super viewDidAppear:animated];
    //self.nextBtn.userInteractionEnabled = NO;
}
- (void)viewDidDisappear:(BOOL)animated {
    [_timer invalidate];
    [_timer2 invalidate];
}


- (void)updateUI {
    frameDefault = self.view.frame;
    self.title = NSLocalizedString(@"VVCtitle", nil);
    [self VerificationText];
    [self.nextBtn setTitle:NSLocalizedString(@"next", nil) forState:UIControlStateNormal];
    self.nextBtn.userInteractionEnabled = NO;
    [self.nextBtn setTitleColor:[UIColor lightGrayColor] forState:UIControlStateNormal];
    
    [self.view addGestureRecognizer:[UtilToolsClss obtainTapGestureRecognizerObjectWithAction:@selector(VVCkeyboardHide:) withTarget:self]];
    
    
    [_againGetSMSBtn setTitle:NSLocalizedString(@"VVCsmsBtn", nil) forState:UIControlStateNormal];
  
    _textContent.text = [NSString stringWithFormat:@"%@+%@ %@.", NSLocalizedString(@"VVCcontent", nil), _VVC_areaNam, _VVC_phoneNumber];

    _timeLabel.textAlignment = NSTextAlignmentCenter;
    _timeLabel.text = NSLocalizedString(@"VVCtimelabel", nil);
    self.againGetSMSBtn.hidden = YES;


    [_timer invalidate];
    [_timer2 invalidate];

    timerCount = 0;
    NSTimer* timer = [NSTimer scheduledTimerWithTimeInterval:60 target:self selector:@selector(showRepeatButton) userInfo:nil repeats:YES]; //60

    self.timeLabel.textColor = [UIColor lightGrayColor];
    NSTimer* timer2 = [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(updateTime) userInfo:nil repeats:YES]; // 1

    _timer = timer;
    _timer2 = timer2;
}




/** 更新计时时间*/
- (void)updateTime {
    timerCount++;
    if (timerCount >= 60) { //60
        [_timer2 invalidate];
        return;
    }
    NSString *second;
    (timerCount == 59) ? ( second = @"VVCsecond") : (second = @"VVCseconds");
    
    self.timeLabel.text = [NSString stringWithFormat:@"%@%i%@", NSLocalizedString(@"VVCtimelablemsg", nil), 60 - timerCount, NSLocalizedString(second, nil)]; //60

    if (timerCount == 30) { //30
        if (self.timeLabel.hidden) {
            _timeLabel.hidden = NO;
        }
    }
}
- (void)showRepeatButton {
    self.timeLabel.hidden = YES;
    self.againGetSMSBtn.hidden = NO;
    [_timer invalidate];
    return;
}


// 输入框内容监控
- (void)textLengthMethod:(UITextField*)textField {
    if (textField.text.length > 0) {
        self.nextBtn.userInteractionEnabled = YES;
        [self.nextBtn setTitleColor:RGB(14, 118, 199, 1) forState:UIControlStateNormal];
        self.VVCbuton.userInteractionEnabled = YES;
        [self.VVCbuton setTitleColor:RGB(14, 118, 199, 11) forState:UIControlStateNormal];
    }
    else {
        self.nextBtn.userInteractionEnabled = NO;
        [self.nextBtn setTitleColor:[UIColor lightGrayColor] forState:UIControlStateNormal];
        self.VVCbuton.userInteractionEnabled = NO;
        [self.VVCbuton setTitleColor:[UIColor lightGrayColor] forState:UIControlStateNormal];
    }

    // 限制长度
    if (textField == self.VerificationText) {
        if (textField.text.length > 4) {
            textField.text = [textField.text substringToIndex:4];
        }
    }
}
// 隐藏
- (void)resignRespondersForText {
    if (isClick) {
        isClick = NO;
    if (SYSTEM_VERSION_EQUAL_TO_W_orH(SCREEN_HEIGHT, @"480.0")) {
            POPBasicAnimation *basicAnim = [POPBasicAnimation animationWithPropertyNamed:kPOPViewFrame];
            basicAnim.toValue = [NSValue valueWithCGRect:CGRectMake(self.view.frame.origin.x, 64, self.view.frame.size.width, self.view.frame.size.height)];
            [self.view pop_addAnimation:basicAnim forKey:@"viewBasicAnim"];
            
            [_VerificationText resignFirstResponder];
    }
    else {
           [self.view endEditing:YES];
     }
        
   }
}

- (void)textFieldDidBeginEditing:(UITextField*)textField
{
    if (!isClick) {
        isClick = YES;
        [self.VerificationText becomeFirstResponder];
    }
    if (SYSTEM_VERSION_EQUAL_TO_W_orH(SCREEN_HEIGHT, @"480.0")) {
        CGRect newFrome = self.view.frame;
        newFrome.origin.y = 40;
        [UIView animateWithDuration:0.24 animations:^{
            [self.view setFrame:newFrome];
        }];
    }
}

// 手势方法键盘隐藏
- (void)VVCkeyboardHide:(UITapGestureRecognizer*)tap
{
    [self resignRespondersForText];
}


- (IBAction)verificationNext:(id)sender {
   
    [self resignRespondersForText];
        // 校验手机短信
        /*[[NetRequestClss sharedNetRequestClss] requestWithUrl:[NSString stringWithFormat:@"userInfo/phoneSmsVerify.asp?loginName=%@&zone=%@&verityCode=%@",_VVC_phoneNumber,_VVC_areaNam,_VerificationText.text] requestWithHeader:nil requestWithParameters:nil requestWithViewController:self requestWithApiID:@"phoneSmsVerify.asp" isMethod:true isListLoaded:true result:^(id objs, int status, NSString *msg) {
            int errorNam = [[[objs objectForKey:@"body"] objectForKey:@"error"] intValue];
            int result   = [[[objs objectForKey:@"body"] objectForKey:@"result"] intValue];
            if (status == 1) {
                if(result == 1){
                    // 验证通过后跳转
                    [_timer invalidate];
                    [_timer2 invalidate];
                    _againGetSMSBtn.hidden = NO;
                    _timeLabel.hidden = YES;
    
                    // 下一页返回的字样
                    UIBarButtonItem* backIetm = [[UIBarButtonItem alloc] init];
                    backIetm.title = NSLocalizedString(@"back", nil);
                    self.navigationItem.backBarButtonItem = backIetm;
                    
                    if ([_VVCsignStr isEqualToString:@"Forget"]) {
                        [self performSegueWithIdentifier:@"gotoForget" sender:self];
                    }
                    else if ([_VVCsignStr isEqualToString:@"Registered"]) {
                        [self performSegueWithIdentifier:@"gotoSubmitVC" sender:self];
                    }

                }else {
                     NSString *messageStr = [NSString stringWithFormat:@"%ddescription",errorNam];
                     [MBProgressHUD showError:NSLocalizedString(messageStr, nil)];
                }
            }else {
                 [MBProgressHUD showError:NSLocalizedString(@"400description", nil)];
            }
        }]; */
    
    NSDictionary *dic = @{@"loginName":_VVC_phoneNumber,
                          @"zone":_VVC_areaNam,
                          @"verityCode":_VerificationText.text};
    [LoginViewModel requestWithUrlForVerification:self andParam:dic success:^(id model) {
        // 验证通过后跳转
        [_timer invalidate];
        [_timer2 invalidate];
        _againGetSMSBtn.hidden = NO;
        _timeLabel.hidden = YES;
        
        // 下一页返回的字样
        UIBarButtonItem* backIetm = [[UIBarButtonItem alloc] init];
        backIetm.title = NSLocalizedString(@"back", nil);
        self.navigationItem.backBarButtonItem = backIetm;
        
        if ([_VVCsignStr isEqualToString:@"Forget"]) {
            [self performSegueWithIdentifier:@"gotoForget" sender:self];
        }
        else if ([_VVCsignStr isEqualToString:@"Registered"]) {
            [self performSegueWithIdentifier:@"gotoSubmitVC" sender:self];
        }
 
    } failure:^(NSString *err) {
         [MBProgressHUD yty_showErrorWithTitle:nil detailsText:err toView:nil];
    }];
    
}
// 传值
- (void)prepareForSegue:(UIStoryboardSegue*)segue sender:(id)sender {
    if ([_VVCsignStr isEqualToString:@"Forget"]) {
        if ([segue.identifier compare:@"gotoForget"] == NO) {
            id vc = segue.destinationViewController;
            [vc setValue:_VVCsignStr forKey:@"FPVCsignStr"];
            [vc setValue:_VVC_areaNam forKey:@"FPVC_areaNam"];
            [vc setValue:_VVC_phoneNumber forKey:@"FPVC_phoneNumber"];
            [vc setValue:self.VerificationText.text forKey:@"FPVC_SMSCode"];
        }
    }
    else if ([_VVCsignStr isEqualToString:@"Registered"]) {
        if ([segue.identifier compare:@"gotoSubmitVC"] == NO) {
            id vc = segue.destinationViewController;
            [vc setValue:_VVCsignStr forKey:@"SVCsignStr"];
            [vc setValue:_VVC_areaNam forKey:@"SVC_areaNam"];
            [vc setValue:_VVC_phoneNumber forKey:@"SVC_phoneNumber"];
            [vc setValue:self.VerificationText.text forKey:@"SVC_SMSCode"];
        }
    }
}

- (IBAction)againGetSMS:(UIButton*)sender {
   
    //[self.view endEditing:YES];

    __weak VerificationVC* verifyVC = self;
   // [self.VerificationText resignFirstResponder];
   verifyVC.VerificationText.clearButtonMode = UITextFieldViewModeNever;
    UIAlertAction* cancelAction = [UIAlertAction actionWithTitle:NSLocalizedString(@"back", nil) style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
        verifyVC.VerificationText.clearButtonMode = UITextFieldViewModeUnlessEditing;
    }];
    UIAlertAction* okAction = [UIAlertAction actionWithTitle:NSLocalizedString(@"sure", nil) style:UIAlertActionStyleDefault handler:^(UIAlertAction* _Nonnull action) {
       
        NSString* str2 = [_VVC_areaNam stringByReplacingOccurrencesOfString:@"+" withString:@""];

        [SMSSDK getVerificationCodeByMethod:SMSGetCodeMethodSMS phoneNumber:_VVC_phoneNumber zone:str2 customIdentifier:nil result:^(NSError* error) {

            if (!error) {
                NSLog(@"获取验证码成功");
                [MBProgressHUD showSuccess:NSLocalizedString(@"send", nil)];

                // [self.VVC_window.rootViewController dismissViewControllerAnimated:YES completion:^{

                verifyVC.againGetSMSBtn.hidden = YES;
                verifyVC.timeLabel.hidden = NO;
                verifyVC.timeLabel.text = NSLocalizedString(@"VVCtimelabel", nil);

                [verifyVC.timer invalidate];
                [verifyVC.timer2 invalidate];

                timerCount = 0;
                NSTimer* timer = [NSTimer scheduledTimerWithTimeInterval:60 target:self selector:@selector(showRepeatButton) userInfo:nil repeats:YES]; //60

                verifyVC.timeLabel.textColor = [UIColor lightGrayColor];
                NSTimer* timer2 = [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(updateTime) userInfo:nil repeats:YES]; // 1

                verifyVC.timer = timer;
                verifyVC.timer2 = timer2;
                [verifyVC.VerificationText becomeFirstResponder];
                //                        }];
            }
            else {
               NSString *messageStr = [NSString stringWithFormat:@"%zidescription",error.code];
                [MBProgressHUD yty_showErrorWithTitle:NSLocalizedString(@"codesenderrtitle", nil) detailsText:NSLocalizedString(messageStr, nil) toView:nil];
            }

        }];
    }];
    NSString* str = [NSString stringWithFormat:@"%@:%@ %@", NSLocalizedString(@"VVCagainGet", nil), _VVC_areaNam, _VVC_phoneNumber];
    UIAlertController* alert = [UIAlertController alertControllerWithTitle:nil message:str preferredStyle:UIAlertControllerStyleAlert]; //NSLocalizedString(@"notice", nil)
    [alert addAction:cancelAction];
    [alert addAction:okAction];
    [self presentViewController:alert animated:YES completion:^{
    }];
}

#pragma get / set

//VerificationText
- (UITextField *)VerificationText {
    if (!_VerificationText) {
    }
    [_VerificationText addYTYanKTextFielStyle1:_VerificationText withString:NSLocalizedString(@"VVCsmsCode", nil)];
     _VerificationText.clearButtonMode = UITextFieldViewModeUnlessEditing;
     _VerificationText.delegate = self;
    [_VerificationText addTarget:self action:@selector(textLengthMethod:) forControlEvents:UIControlEventEditingChanged];
    [_VerificationText setInputAccessoryView:self.VVCtoolbar];
    return _VerificationText;
}

- (UIToolbar *)VVCtoolbar {
    if (!_VVCtoolbar) {
         _VVCtoolbar = [[UIToolbar alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, 30)];
         _VVCtoolbar.backgroundColor = RGB(28, 28, 28, 1);
        [_VVCtoolbar setBarStyle:UIBarStyleBlack];
        [_VVCtoolbar addSubview:self.VVCbuton];
    }
    return _VVCtoolbar;
}

- (UIButton *)VVCbuton {
    if (!_VVCbuton) {
    _VVCbuton = [[UIButton alloc] initWithFrame:CGRectMake(SCREEN_WIDTH - 38 - 20, 0, 50, 30)];
    _VVCbuton.titleLabel.font = [UIFont systemFontOfSize:14.f];
    [_VVCbuton setTitle:NSLocalizedString(@"next", @"下一页") forState:UIControlStateNormal];
    [_VVCbuton addTarget:self action:@selector(verificationNext:) forControlEvents:UIControlEventTouchDown];
    [_VVCbuton setUserInteractionEnabled:NO];
    [_VVCbuton setTitleColor:[UIColor lightGrayColor] forState:UIControlStateNormal];
    }
    return _VVCbuton;
}



@end
